using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ERP.EquipmentManage.Dtos;
using ERP.ERPModels.EquipmentManage;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Microsoft.Extensions.Logging;

namespace ERP.EquipmentManage
{
    /// <summary>
    /// 维护计划与设备点检项目关联服务实现
    /// </summary>
    public class PlanDvsubjectService : ApplicationService, IPlanDvsubjectService
    {
        private readonly IRepository<EquipmentMaintenancePlanDvsubject, int> _planDvsubjectRepository;
        private readonly IRepository<Dvsubject, int> _dvsubjectRepository;
        private readonly ILogger<PlanDvsubjectService> _logger;

        public PlanDvsubjectService(
            IRepository<EquipmentMaintenancePlanDvsubject, int> planDvsubjectRepository,
            IRepository<Dvsubject, int> dvsubjectRepository,
            ILogger<PlanDvsubjectService> logger)
        {
            _planDvsubjectRepository = planDvsubjectRepository;
            _dvsubjectRepository = dvsubjectRepository;
            _logger = logger;
        }

        /// <summary>
        /// 保存计划的设备点检项目列表
        /// </summary>
        public async Task SavePlanDvsubjectsAsync(string planCode, List<int> dvsubjectIds)
        {
            _logger.LogInformation("开始保存计划项目: 计划编码={PlanCode}", planCode);
            _logger.LogInformation("项目ID列表: {@DvsubjectIds}", dvsubjectIds);
            
            try
            {
                // 先删除该计划下的所有项目
                var existingItems = await _planDvsubjectRepository.GetListAsync(x => x.PlanCode == planCode);
                _logger.LogInformation("找到现有项目数量: {Count}", existingItems.Count);
                
                if (existingItems.Any())
                {
                    await _planDvsubjectRepository.DeleteManyAsync(existingItems);
                    _logger.LogInformation("删除现有项目成功");
                }

                // 再添加新的项目关联
                if (dvsubjectIds != null && dvsubjectIds.Any())
                {
                    _logger.LogInformation("开始添加新项目，数量: {Count}", dvsubjectIds.Count);
                    
                    var newItems = dvsubjectIds.Select((id, index) => new EquipmentMaintenancePlanDvsubject
                    {
                        PlanCode = planCode,
                        DvsubjectId = id,
                        CreatedAt = DateTime.Now,
                        Sort = index + 1
                    }).ToList();

                    _logger.LogInformation("创建新项目关联: {@NewItems}", newItems.Select(x => new { x.PlanCode, x.DvsubjectId, x.Sort }));
                    
                    await _planDvsubjectRepository.InsertManyAsync(newItems);
                    _logger.LogInformation("插入新项目成功");
                }

                await CurrentUnitOfWork.SaveChangesAsync();
                _logger.LogInformation("保存工作单元成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存计划项目失败: {Message}", ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 获取计划的设备点检项目列表
        /// </summary>
        public async Task<List<DvsubjectDto>> GetPlanDvsubjectsAsync(string planCode)
        {
            _logger.LogInformation("开始获取计划项目列表: {PlanCode}", planCode);
            
            try
            {
                // 获取关联关系
                var planDvsubjects = await _planDvsubjectRepository.GetListAsync(x => x.PlanCode == planCode);
                _logger.LogInformation("找到关联项目数量: {Count}", planDvsubjects.Count);
                
                if (!planDvsubjects.Any())
                {
                    _logger.LogInformation("没有找到关联项目");
                    return new List<DvsubjectDto>();
                }

                // 获取项目ID列表
                var dvsubjectIds = planDvsubjects.Select(x => x.DvsubjectId).ToList();
                _logger.LogInformation("项目ID列表: {@DvsubjectIds}", dvsubjectIds);

                // 查询设备点检项目详情
                var dvsubjects = await _dvsubjectRepository.GetListAsync(x => dvsubjectIds.Contains(x.Id));
                _logger.LogInformation("查询到的项目详情数量: {Count}", dvsubjects.Count);

                // 创建结果列表
                var result = new List<DvsubjectDto>();
                
                // 按照保存时的排序遍历关联项目
                foreach (var planDvsubject in planDvsubjects.OrderBy(x => x.Sort))
                {
                    var dvsubject = dvsubjects.FirstOrDefault(d => d.Id == planDvsubject.DvsubjectId);
                    if (dvsubject != null)
                    {
                        try
                        {
                            // 手动创建DTO对象，避免AutoMapper可能的问题
                            var dto = new DvsubjectDto
                            {
                                Id = dvsubject.Id,
                                Subcode = dvsubject.Subcode ?? string.Empty,
                                Subname = dvsubject.Subname ?? string.Empty,
                                Subtype = dvsubject.Subtype ?? string.Empty,
                                Isdel = dvsubject.Isdel,
                                Subcontext = dvsubject.Subcontext ?? string.Empty,
                                Subarea = dvsubject.Subarea ?? string.Empty
                            };
                            
                            result.Add(dto);
                            _logger.LogInformation("成功创建DTO: {Id}={DvsubjectId}, {Subcode}={Subcode}", 
                                dto.Id, dvsubject.Id, dto.Subcode, dvsubject.Subcode);
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, "创建DTO失败，项目ID: {DvsubjectId}", dvsubject.Id);
                            throw;
                        }
                    }
                    else
                    {
                        _logger.LogWarning("未找到项目详情，项目ID: {DvsubjectId}", planDvsubject.DvsubjectId);
                    }
                }

                _logger.LogInformation("返回结果数量: {Count}", result.Count);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取计划项目列表失败: {Message}", ex.Message);
                throw;
            }
        }

        /// <summary>
        /// 删除计划的某个设备点检项目
        /// </summary>
        public async Task RemovePlanDvsubjectAsync(string planCode, int dvsubjectId)
        {
            var item = await _planDvsubjectRepository.FirstOrDefaultAsync(x => x.PlanCode == planCode && x.DvsubjectId == dvsubjectId);
            if (item != null)
            {
                await _planDvsubjectRepository.DeleteAsync(item);
                await CurrentUnitOfWork.SaveChangesAsync();
            }
        }

        /// <summary>
        /// 添加项目到计划
        /// </summary>
        public async Task AddPlanDvsubjectAsync(string planCode, int dvsubjectId)
        {
            // 检查是否已存在
            var existing = await _planDvsubjectRepository.FirstOrDefaultAsync(x => x.PlanCode == planCode && x.DvsubjectId == dvsubjectId);
            if (existing != null)
            {
                throw new Exception("该项目已添加到计划中");
            }

            // 获取当前计划下项目的最大排序号
            var maxSort = await _planDvsubjectRepository.GetListAsync(x => x.PlanCode == planCode);
            var nextSort = maxSort.Any() ? maxSort.Max(x => x.Sort) + 1 : 1;

            var newItem = new EquipmentMaintenancePlanDvsubject
            {
                PlanCode = planCode,
                DvsubjectId = dvsubjectId,
                CreatedAt = DateTime.Now,
                Sort = nextSort
            };

            await _planDvsubjectRepository.InsertAsync(newItem);
            await CurrentUnitOfWork.SaveChangesAsync();
        }
    }
} 